package com.kotodama.infrastructure.tenant.filter;

import com.kotodama.infrastructure.tenant.context.TenantContext;
import org.hibernate.Session;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PostLoadEventListener;
import org.hibernate.event.spi.PreLoadEvent;
import org.hibernate.event.spi.PreLoadEventListener;
import org.springframework.stereotype.Component;

/**
 * Hibernate事件监听器，自动启用租户过滤器
 */
@Component
public class TenantFilterInterceptor implements PreLoadEventListener, PostLoadEventListener {

    private static final String TENANT_FILTER_NAME = "tenantFilter";
    private static final String TENANT_PARAMETER_NAME = "tenantId";

    @Override
    public void onPreLoad(PreLoadEvent event) {
        enableTenantFilter(event.getSession());
    }

    @Override
    public void onPostLoad(PostLoadEvent event) {
        enableTenantFilter(event.getSession());
    }

    /**
     * 启用租户过滤器
     * 
     * @param session Hibernate会话
     */
    private void enableTenantFilter(Session session) {
        String tenantId = TenantContext.getTenantId();
        if (tenantId != null && !tenantId.isEmpty()) {
            session.enableFilter(TENANT_FILTER_NAME)
                    .setParameter(TENANT_PARAMETER_NAME, tenantId);
        }
    }
}